package com.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.pojo.Orders;
import com.service.CartService;
import com.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping("/ali")
public class AliPayController {
    @Autowired
    private Orders order;
    @Autowired
    private OrdersService ordersService;
    private String serverUrl = "https://openapi.alipaydev.com/gateway.do"; // 支付宝的网关地址
    private String APP_ID = "2016101000656227";
    private String APP_PRIVATE_KEY = "MIIEuwIBADANBgkqhkiG9w0BAQEFAASCBKUwggShAgEAAoIBAQCQ0XDs0oV54+TwyNJkCZxoZa/bXmK0SvIC9+reKRJRcUqSpe9JpTBD2E2UNstBPxJlreUhJrT23K2IsvnMixaBpvQ6CI82k0iCKanYqkQ/gyNeWvCjRRogdr9zbzxHiB1pYAqRzrtp0rZ0eN+6RSuZ0qsPtcSaAY+6wEqQRRvxHiXvJunnF+tln4UgO+mUlxWdskmlML1bjqv8hXvLDotytzVEx3A0TiSUQWBUNAToqRAtx8aAaM/bPTLMFOmRHVQ6Kxb+FaByq2WqI6+lZXmVZuvhUiEzN2ThyDE+uFdEF8OvIOabgOsJViUgzUk8WHR/G1T29PIvKQbJAxLpaVBJAgMBAAECggEACE1JaPoklrk+zaLllMCMS9vQegXuKKHHP+5Qc43tM+gHu2Jx1kn2+1yyDdYaTtI7zsJqST070I8UD6sa8OPkVWhpxc3pz9ofpP6YcwhHw1BUPbt+4g07EzNbhFWTIhKmhPzxfixYyBdBSGoJgVcnybiu/8aOz7lZMP6HB8A+etMGa1FldB37pSF/4y4FpNLCL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SET = "utf-8"; // 数据的编码
    private String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArC+n7jVK2EtqhtynNGDxdFVYrwT8jP2gu3VsRu7CSfdsAfuDTrwmeuKeaQCBQ19gSAslwTzfip8ebIsiA6jnhRrpNbd+c3FxBxHR6tB6pG2tvBPB6EtQAStRTjPWkiTF1laTbcynuKsiW8X4dgX92PxPfW/Fx8bHgDgxrEBhrURUtZHuQh6VBdUyLHAnpVKU+zQ06p+h4H4O/Ch+fv0KAzAHe9Z1XVot2hswa+UJM1H2am5y2DU5K1gw3s8anGoOMnc4tFsXW4yDEZQrspxbhtLiU7tWc4fvd4GEQ7Ye7OoPIWtUZq1iyra8TMtT2KIhyYRqj+1K21HyMsJkmf0cvwIDAQAB"; // 支付宝的公钥
    private String SINGTYP = "RSA2"; // 签名算法


    @RequestMapping("/pay")
    public void pay(String id,HttpServletRequest request, HttpServletResponse httpResponse) throws Exception {
        System.out.println("AliPayController.pay");
        System.out.println(id);
        String oid=request.getParameter("id");
        System.out.println(oid);
        order=ordersService.getOrdersById(oid);

        if (!StringUtils.isEmpty(id)) {

            // 1.根据订单ID查询订单对象
            Orders orders = ordersService.getOrdersById(id);
             System.out.println(orders);
            // 1.封装请求支付宝的参数
            AlipayClient alipayClient = new DefaultAlipayClient(
                    serverUrl, // 支付宝的网关地址,注意我们这里dev测试
                    APP_ID, // 商家的appid
                    APP_PRIVATE_KEY, // 商家私钥
                    FORMAT, // 数据传递的格式
                    CHARSET, // 请求数据的编码
                    ALIPAY_PUBLIC_KEY, // 支付宝的公钥
                    SINGTYP // 签名的类型
            );  //获得初始化的AlipayClient


            // 2.创建一个请求对象
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest(); //创建API对应的request

            // 3.设置同步异步跳转的地址
            alipayRequest.setReturnUrl("http://localhost:8888/house/index/pay?id="+oid); // 支付成功后跳转同步跳转

            // 支付宝发送的异同通知需要作为更新订单的状态
            alipayRequest.setNotifyUrl("http://localhost:8888/house/ali/updateOrderStatus"); // 支付宝会调用这个接口通知商家，支付的状态
            String timeout_express = "10m";
            // 4、订单的信息
            alipayRequest.setBizContent(
                    "{\"out_trade_no\":\""+id+"\","
                            + "\"total_amount\":\""+order.getTotal()+"\","
                            + " \"subject\":\"爱家政\","
                            + "\"body\":\"做饭\","
                           // + "\"timeout_express\":\"" + timeout_express + "\","
                            + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

            String form = "";
            try {
                // 获取一个登陆页面
                form = alipayClient.pageExecute(alipayRequest).getBody();  //调用SDK生成表单
                System.out.println(form);
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
            // 把登录页面响应给用户
            httpResponse.setContentType("text/html;charset=" + CHARSET);

            httpResponse.getWriter().write(form); //直接将完整的表单html输出到页面

            httpResponse.getWriter().flush();

            httpResponse.getWriter().close();

        } else {
//          //  throw new ShopException(1002, "订单为不能为空");
       }
    }

    // 必须确保这个解耦由支付宝来调用，所以需要做延签
    @PostMapping("/updateOrderStatus")
    public void updateOrderStatus(HttpServletRequest request) throws AlipayApiException {
        System.out.println("AliPayController.updateOrderStatus");

        // 1.获取支付宝发送的参数了
        Map<String, String[]> parameterMap = request.getParameterMap();

        // 2、把支付宝传递古来的参数放到一个Map<Sring,String>中
        Map<String, String> paramMap = new HashMap<>();
        Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();
        for (Map.Entry<String, String[]> entry : entries) {
            paramMap.put(entry.getKey(), entry.getValue()[0]);
        }

        // 3延签，验证这个请你去是支付宝发送的
        boolean signVerified = AlipaySignature.rsaCheckV1(paramMap, ALIPAY_PUBLIC_KEY, CHARSET, SINGTYP); //调用SDK验证签名

        if (signVerified) {
            // 1.获取交易状态
            String trade_status = request.getParameter("trade_status");

            System.out.println(trade_status);
            // 2.判断状态值
            if ("TRADE_SUCCESS".equals(trade_status)) {
                // 支付成功，修改订单的状态
                System.out.println("延签通过，修改订单的状态。。。");
                String id = paramMap.get("111111111"); // 获取订单id
                Orders orders=ordersService.getOrdersById(id);
                ordersService.updateOrders(orders);
            }
        } else {
            System.out.println("这是一个非法的请求。。。");
        }
    }
}
